//
//  NSObject+MSObject.m
//  PeopleForTheFirstMall
//
//  Created by iOS on 2020/7/2.
//  Copyright © 2020 MS. All rights reserved.
//

#import "NSObject+MSObject.h"

@implementation NSObject (MSObject)


#pragma - mark - 获取字符串长度

- (NSInteger)ms_getStringLengthWithString:(NSString *)string
{
    __block NSInteger stringLength = 0;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop)
     {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff)
                                {
                                    if (substring.length > 1)
                                    {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f)
                                        {
                                            stringLength += 1;
                                        }
                                        else
                                        {
                                            stringLength += 1;
                                        }
                                    }
                                    else
                                    {
                                        stringLength += 1;
                                    }
                                }
                                else if (substring.length > 1)
                                {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3)
                                    {
                                        stringLength += 1;
                                    }
                                    else
                                    {
                                        stringLength += 1;
                                    }
                                }
                                else
                                {
                                    if (0x2100 <= hs && hs <= 0x27ff)
                                    {
                                        stringLength += 1;
                                    }
                                    else if (0x2B05 <= hs && hs <= 0x2b07)
                                    {
                                        stringLength += 1;
                                    }
                                    else if (0x2934 <= hs && hs <= 0x2935)
                                    {
                                        stringLength += 1;
                                    }
                                    else if (0x3297 <= hs && hs <= 0x3299)
                                    {
                                        stringLength += 1;
                                    }
                                    else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50)
                                    {
                                        stringLength += 1;
                                    }
                                    else
                                    {
                                        stringLength += 1;
                                    }
                                }
    }];
    
    return stringLength;
}


#pragma mark - 转换为JSON
/** 转化为JSON data */
- (NSData *)ms_JSONData
{
    if ([self isKindOfClass:[NSString class]])
    {
        return [((NSString *)self) dataUsingEncoding:NSUTF8StringEncoding];
    }
    else if ([self isKindOfClass:[NSData class]])
    {
        return (NSData *)self;
    }
    
    return [NSJSONSerialization dataWithJSONObject:[self ms_JSONObject]
                                           options:kNilOptions
                                             error:nil];
}
/** 转化为数组或字典 */
- (id)ms_JSONObject
{
    if ([self isKindOfClass:[NSString class]])
    {
        return [NSJSONSerialization JSONObjectWithData:[((NSString *)self) dataUsingEncoding:NSUTF8StringEncoding]
                                               options:kNilOptions
                                                 error:nil];
    }
    else if ([self isKindOfClass:[NSData class]])
    {
        return [NSJSONSerialization JSONObjectWithData:(NSData *)self
                                               options:kNilOptions
                                                 error:nil];
    }
    
    return self;
}
/** 转化为JSON字符串，如需去收尾空格和换行调用 removeleadingAndTrailingSpaces */
- (NSString *)ms_JSONString
{
    if ([self isKindOfClass:[NSString class]])
    {
        return (NSString *)self;
    }
    else if ([self isKindOfClass:[NSData class]])
    {
        return [[NSString alloc] initWithData:(NSData *)self
                                     encoding:NSUTF8StringEncoding];
    }
    
    return [[NSString alloc] initWithData:[self ms_JSONData]
                                 encoding:NSUTF8StringEncoding];
}
/** 转化为JSON字符串并去掉 \ */
- (NSString *)ms_JSONString_Filter
{
    NSString *string = [self ms_JSONString];
    
    NSScanner *scanner = [NSScanner scannerWithString:string];
    NSString *text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<"intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">"intoString:&text];
        //替换字符
        string = [string stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text]withString:@""];
    }
//    NSString *regEx = @"<([^>]*)>";
//    html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    return string;
}


#pragma mark - 读取本地JSON文件

- (id)ms_JSONObjectForResource:(NSString *)name
                        ofType:(NSString *)type
{
    NSString *path = [[NSBundle mainBundle] pathForResource:name
                                                     ofType:type];
    NSData *jsonData = [[NSData alloc] initWithContentsOfFile:path];
    NSError *error;
    id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData
                                                 options:NSJSONReadingMutableContainers
                                                   error:&error];
    if (!jsonData || error)
    {
        //DLog(@"JSON解码失败");
        return nil;
    }
    else
    {
        return jsonObj;
    }
}


#pragma mark -
/** 判断两个时间戳是否为同一天 */
- (BOOL)ms_isSameDay:(long)iTime1
               Time2:(long)iTime2
{
    NSDate *pDate1 = [NSDate dateWithTimeIntervalSince1970:iTime1];
    NSDate *pDate2 = [NSDate dateWithTimeIntervalSince1970:iTime2];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags
                                          fromDate:pDate1];
    NSDateComponents* comp2 = [calendar components:unitFlags
                                          fromDate:pDate2];
    
    return [comp1 day] == [comp2 day] && [comp1 month] == [comp2 month] && [comp1 year]  == [comp2 year];
}
/** 判断时间戳是否为未来时间 */
- (BOOL)ms_isFutureDays:(long)iTime
{
    NSDate *pDate1 = [NSDate dateWithTimeIntervalSince1970:iTime];
    NSDate *pDate2 = [NSDate date];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags
                                          fromDate:pDate1];
    NSDateComponents* comp2 = [calendar components:unitFlags
                                          fromDate:pDate2];
    
    return [comp1 day] > [comp2 day] && [comp1 month] == [comp2 month] && [comp1 year]  == [comp2 year];
}
/** 时间戳格式化为 年月日时分秒JSONString */
- (NSString *)ms_JSONStringWithTimeInterval:(double)timeInterval
{
    int t = timeInterval;
    if (t < 0) t = 0;
    int year = 0;
    int month = 0;
    int day = 0;
    int hours = 0;
    int minutes = 0;
    int seconds = 0;
    
    if (t > 0)
    {
        year = t / (60 * 60 * 24 * 30 * 12);
        t = t % (60 * 60 * 24 * 30 * 12);
        month = t / (60 * 60 * 24 * 30);
        t = t % (60 * 60 * 24 * 30);
        day = t / (60 * 60 * 24);
        t = t % (60 * 60 * 24);
        hours = t / (60 * 60);
        t = t % (60 * 60);
        minutes = t / 60;
        t = t % 60;
        seconds = t;
    }
    
    return [@{@"year" : @(year), @"month" : @(month), @"day" : @(day), @"hours" : @(hours), @"minutes" : @(minutes), @"seconds" : @(seconds)} ms_JSONString];
}
/** 获取当年当月第一天和最后一天 */
- (NSArray *)ms_getMonthFirstAndLastDayWith:(NSString *)dateStr
{
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd"];
    NSDate *newDate=[format dateFromString:dateStr];
    double interval = 0;
    NSDate *firstDate = nil;
    NSDate *lastDate = nil;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    if ([calendar rangeOfUnit:NSCalendarUnitMonth startDate:&firstDate interval:&interval forDate:newDate])
    {
        lastDate = [firstDate dateByAddingTimeInterval:interval - 1];
    }
    else
    {
        return @[@"",@""];
    }
    
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *firstString = [myDateFormatter stringFromDate: firstDate];
    NSString *lastString = [myDateFormatter stringFromDate: lastDate];
    
    return @[firstString, lastString];
}


#pragma mark - AVAudio

/** 播报 */
- (void)ms_speech:(NSString *)string
{
    if (string && string.length > 0)
    {
        
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                               error:nil];
        [[AVAudioSession sharedInstance] setActive:YES
                                             error:nil];
        
        AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:string];
        utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
        utterance.pitchMultiplier = 0.1; // 声调
        utterance.volume = 1;// 音量
        utterance.rate = 0.5;// 语速
        utterance.pitchMultiplier = 1.1;
        
        AVSpeechSynthesizer *avSpeech = [[AVSpeechSynthesizer alloc] init];
        [avSpeech speakUtterance:utterance];
    }
}

/// 播放通知铃声
- (void)ms_playSoundWithFilename:(NSString *)filename
                   fileExtension:(NSString *)fileExtension
{
    // 系统值 kSystemSoundID_Vibrate = 0x00000FFF
    SystemSoundID sound = 1;
    // 转换 URL
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:filename ofType:fileExtension];
    NSURL *soundURL = [NSURL fileURLWithPath:soundFilePath];
    // 生成系统音效id
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &sound);
    // 播放系统音效
    AudioServicesPlaySystemSound(sound);
}

@end
